package com.keeping.aiimagery.controller;

import com.keeping.aiimagery.entity.Sms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@RestController
@CrossOrigin
@RequestMapping("/user")
@ConfigurationProperties(prefix = "application.yml")
public class SmsController {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * 发送手机验证码
     * @param phone 手机号码
     * @return 1表示成功，0表示失败
     */
    @GetMapping("/sendSms")
    public String SmsTest(@RequestParam("phone") String phone){
        //发送短信
        System.out.println(phone);
        if(phone=="")
        {
            return "error";
        }
        boolean result = Sms.sendSmsUtil(phone);

        if (result == false) {// 发送不成功
            return "0";
        }
        System.out.println(phone);
        // 获取验证码
        int code =  Sms.getCode();
        Map<String,Object> map=new HashMap<>();
        // 将数据存入redis
        map.put(phone,code+"");
        //用phoneNumber来做键，可以做到唯一性
        stringRedisTemplate.opsForHash().putAll(phone,map);
        // 设置redis过期时间,这个时间是秒为单位的，我现在设置5分钟之内有效，过了就会自动删除
        stringRedisTemplate.expire(phone, 60*5, TimeUnit.SECONDS);
        System.out.println(code);
        return "OK";

    }
    /**
     * 校验验证码
     * @param phoneNumber
     * @param checkSMSCode
     * @return
     */
    @GetMapping(value = "/checkSMSCode")
    @ResponseBody
    public String checkSMSCode(@RequestParam("phone") String phoneNumber,@RequestParam("code") String checkSMSCode) {

        // 服务器放入的验证码
        //从redis中取出以电话号码为key，验证码为value的值
        Map<Object, Object> map=stringRedisTemplate.opsForHash().entries(phoneNumber);
        String serverCheckCode =(String) map.get(phoneNumber);


        if (serverCheckCode == null || serverCheckCode.equals("")) {
            return "CodeError";
        }
        // 验证码不匹配
        if (!checkSMSCode.equals(serverCheckCode)) {
            return "CodeError";
        }else {
            //如果验证成功就删除验证码
            stringRedisTemplate.opsForHash().delete(phoneNumber,phoneNumber);
        }


        return "OK";

    }

}
